﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QianBuo.Lottery.Web.Commen;
using QianBuo.Lottery.Web.Models;
using QianBuo.Lottery.Web.Models.Play;
using Code.Models;
using Code.BLL;
using System.Web.Routing;

namespace QianBuo.Lottery.Web.Controllers
{
    public class PlayController : BaseController
    {
        //
        // GET: /Play/

        public ActionResult Index(LotteryType? id,PlayType_E? p1)
        {
            var LM = CacheManage.Lottery;
            if (p1.HasValue)
            {
                TempData["playid"] = (int)p1.Value;
                return RedirectToAction("Index", new { id = id });
            }

            Code.Models.Lottery lottery = null;
            if (!id.HasValue)
            {
                lottery = LM.Values.FirstOrDefault(p => p.State == (short)LotteryState.Normal);
                if (lottery == null)
                {
                    ViewData["Error_Msg"] = "抱歉！\\r\\n目前暂无彩种开放！".AlertOffPage();
                    return View("Error");
                }
            }
            else
            {
                lottery = LM[id.Value];
                if (lottery == null)
                    return RedirectToAction("Index", new { id=""});
                else if (lottery.State != (int)LotteryState.Normal)
                {
                    ViewData["Error_Msg"] = "抱歉！\\r\\n该彩种已关闭！".AlertOffPage() + Url.Action("Index", new { id=""}).Redirect();
                    return View("Error");
                }
            }


            IssueManage IM = new IssueManage();
            var PM = CacheManage.PlayType;

            TempData["Play_Lottery"] = lottery.Alias;

            var plays = new ModelNameValue<int, NameValueItem<int, string>>();
            var playitems = PM.Values.Where(p => p.State == (short)PlayTypeState.Normal && p.LotteryID == lottery.ID)
                .OrderBy(p=>p.ID).OrderBy(p => p.Sort).Select(p => new NameValueItem<int, NameValueItem<int, string>>
                {
                    Key = p.ID,
                    Value = new NameValueItem<int, string> { Key = p.PlayTypeListID, Value = p.PlayTypeList.Alias ?? p.PlayTypeList.Name }
                }).ToArray();
            if (playitems != null&&playitems.Length>0)
                plays.AddRange(playitems);

            int? playid = (TempData["playid"] as int?) ?? plays.Select(p => p.Value.Key as int?).FirstOrDefault() ?? -1;
            var ratio = CacheManage.Ratio[base.LoginUser.Ratio];
            var model = new PlayModel
                {
                    Ratio = (double) base.LoginUser.Ratio,
                    RatioName = ratio.Name,
                    LotteryID = lottery.ID,
                    ForwardEnd = lottery.ForwardEnd,
                    LotteryName = lottery.Name,
                    OpenWinDelay = lottery.OpenWinDelayTime,
                    SingleBetMoney = (double) ratio.RadixMoney,
                    PlayType = plays,
                    PlayID = playid.Value,
                    Bet = new BetModel() {SingleMultiply = 1},
                    IsSinglePlay = "true".Equals(TempData["singleplay"] as string),
                    OpenCodeLen = lottery.OpenCodeLength,

                    BackMoneyToWinMoneyEnable = CacheManage.OptionSite[Option_Site_Key.Site_BackMoneyToWinMoney_Enable].ToBool(false),
                    BackMoneyToWinMoneyStep = CacheManage.OptionSite[Option_Site_Key.Site_BackMoneyToWinMoney_Step].ToDouble(0.1),
                };
            return View("Index",model);
        }

        public ActionResult SinglePlay(LotteryType? id, PlayType_E? p1)
        {
            if(p1.HasValue)
                TempData["playid"] = (int)p1.Value;
            TempData["singleplay"] = "true";
            var rs= Index(id,null);
            return rs;
        }

        [HttpPost]
        public JsonResult Index(PlayModel model,FormCollection form)
        {
            model.PlayType = new ModelNameValue<int, NameValueItem<int, string>>();
            var playitems = CacheManage.PlayType.Values.Where(p => p.State == (short)PlayTypeState.Normal && p.LotteryID == model.LotteryID)
                .OrderBy(p => p.PlayTypeListID).Select(p => new NameValueItem<int, NameValueItem<int, string>>
                {
                    Key = p.ID,
                    Value = new NameValueItem<int, string> { Key = p.PlayTypeListID, Value = p.PlayTypeList.Alias ?? p.PlayTypeList.Name }
                }).ToArray();
            if (playitems != null && playitems.Length > 0)
                model.PlayType.AddRange(playitems);

            if (LoginUser.State != UserState.Normal)
            {
                var state = (UserState)LoginUser.State;
                var massage = state == UserState.Freez ? "您的金额已冻结，请先解冻!" : string.Format("您已被{0}，请与{1}联系！", state.GetName(), state == UserState.Locked_Manage ? "您的上级代理" : "管理员");
                return Json(new { Message=massage, sate = false}, JsonRequestBehavior.AllowGet);
            }
            TempData["Play_Lottery"] = ((LotteryType)model.LotteryID).ToString();
            if (ModelState.IsValid)
            {
                try
                {
                    Scheme scheme = new Scheme()
                    {
                        ID = Guid.NewGuid(),
                        Share = 1,
                        UserID = base.LoginUserID,
                        IssueID = model.Bet.IssueID,
                        Multiple = model.Bet.SingleMultiply,
                        ConsumptionRatio = base.LoginUser.Ratio,
                        WinModelID = base.LoginUser.WinModelID,
                        LotteryID = model.LotteryID
                    };

                    List<Scheme_Detail> plays = new List<Scheme_Detail>();
                    foreach (var item in model.Bet.PlayList)
                    {
                        //PlayTypeListID:Number:IsCompound:BackMoneyToWinMoney
                        var tp = item.Split(':');
                        int playtypelistid = int.Parse(tp[0]);
                        int playtypeid = model.PlayType.FirstOrDefault(p => p.Value.Key == playtypelistid).Key;
                        short iscompound = short.Parse(tp[2]);
                        Scheme_Detail detali = new Scheme_Detail
                        {
                            PlayTypeID = playtypeid,
                            ChoseNumber = tp[1],
                            PlayType = new PlayType()
                            {
                                ID = playtypeid,
                                PlayTypeListID = playtypelistid,
                            },
                            IsCompound = iscompound,
                        };

                        decimal backtowin;
                        if (item.Length > 2 && decimal.TryParse(tp[3], out backtowin))
                            detali.BackMoneyToWinMoney = backtowin;

                        if (model.PlayType.ContainsKey(detali.PlayTypeID))
                            plays.Add(detali);
                        else
                            ModelState.AddModelError("PlayError", "不存在该玩法");
                    }

                    if (ModelState.IsValid)
                    {
                        //当期购买
                        if (!model.Bet.Chase)
                        {
                            SchemeManage SM = new SchemeManage();

                            int rs = SM.Add(scheme, plays);
                            if (rs < 0)
                                ModelState.AddModelError("PlayError", "系统错误");
                        }
                        else  //追号
                        {
                            List<ChaseTask_Detail> chases = new List<ChaseTask_Detail>();
                            foreach (var item in model.Bet.Chases)
                            {
                                var multiply = int.Parse(form["Bet.ChaseMultiply." + item]);
                                var chase = new ChaseTask_Detail
                                {
                                    IssueID = item,
                                    Multiple = multiply,
                                    Share = 1,
                                    UserChoseShare = 1,
                                };
                                chases.Add(chase);
                            }

                            ChaseManage CM = new ChaseManage();

                            var task = new ChaseTask
                            {
                                ID = Guid.NewGuid(),
                                LotteryID = model.LotteryID,
                                StopWin = model.Bet.StopWin ? 0 : -1,
                                ConsumptionRatio = base.LoginUser.Ratio,
                                UserID = LoginUserID,
                                WinModelID = base.LoginUser.WinModelID,
                            };

                            var rs = CM.AddChaseTask(task, plays, chases);
                            if (rs < 0)
                                ModelState.AddModelError("PlayError", "系统错误");
                        }

                    }
                }
                catch (FormatException)
                { ModelState.AddModelError("PlayError", "数据格式不正确"); }
                catch (ArgumentNullException)
                { ModelState.AddModelError("PlayError", "系统错误"); }
                catch (BetValidateException e)
                {
                    var msg1 = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_BetError].Value;
                    if (string.IsNullOrEmpty(msg1))
                        msg1 = e.Message;
                    ModelState.AddModelError("PlayError", msg1); 
                }
                catch (AppException e)
                { ModelState.AddModelError("PlayError", e.Message); }
                catch (Exception)
                { ModelState.AddModelError("PlayError", "系统异常,稍后再试."); }
            }


            string msg = "认购成功！";
            if (!ModelState.IsValid)
                msg = ModelState.Select(p => p.Value.Errors).First(p => p.Count > 0).First().ErrorMessage;

            var result = new
            {
                Message = msg,
                State = ModelState.IsValid
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [OutputCache(Duration = 60, VaryByParam = "id;p1")]
        public ActionResult Play(LotteryType id, PlayType_E p1)
        {
            var PM = CacheManage.Playlist;

            if (!PM.ContainsKey(p1))
            {
                Response.Write("不存在该玩法！");
                Response.End();
            }
            var play = CacheManage.PlayType.FirstOrDefault(p => p.Value.LotteryID == (int)id && p.Value.PlayTypeListID == (int)p1);
            if (play == null)
                return new EmptyResult();
            var type = PM[p1];
            var model = new PlayTypeModel
            {
                ID = type.ID,
                PlayID = play.Key,
                Name = type.Name,
                InputFile = type.InputPanel,
                Lottery = id,
                Remark = type.Remark,
            };

            return View(type.InputPanel, model);
        }

        public JsonResult ChaseIssue(int id)
        {
            IssueManage IM = new IssueManage();
            LotteryManage LM = new LotteryManage();

            var l = CacheManage.Lottery.Values.FirstOrDefault(p => p.ID == id);
            if (l == null)
                return Json(new { Error = true, Text = "无该彩种" }, JsonRequestBehavior.AllowGet);

            var option = CacheManage.OptionSite;

            var maxchasetask = option[Option_Site_Key.User_MaxChaseTaskMun].ToInt32(400);

            var items = IM.Select(s => s.Where(p => p.LotteryID == id && p.EndTime > DateTime.Now.AddSeconds(l.ForwardEnd) && p.State == (short)IssueState.Normal).Take(400).ToArray());
            var issues = items.Select(p => new { p.ID, Number = p.FormatIssueName, p.StartTime, EndTime = p.EndTime.AddSeconds(-l.ForwardEnd) }).OrderBy(p=>p.StartTime).ToArray();
            if (issues.Length > 1)
                return Json(issues, JsonRequestBehavior.AllowGet);
            else
                return Json(new { Error = true, Text = "暂无期号" }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult CurrentIssue(int id)
        {
            object obj = null;
            var LM = CacheManage.Lottery;
            var l = LM.Values.FirstOrDefault(p => p.ID == id);
            if (l != null)
            {
                IssueManage IM = new IssueManage();
                var issue = IM.GetCurrentIssue((LotteryType)id);
                var nest = IM.GetNextIssue((LotteryType)id);
                if (issue != null)
                {
                    DateTime end = issue.EndTime.AddSeconds(-l.ForwardEnd);
                    obj = new
                    {
                        issue.ID,
                        Number = issue.FormatIssueName,
                        StartTime = issue.StartTime.ToString("MM/dd/yyyy HH:mm:ss"),
                        EndTime = (DateTime.Now > end ? DateTime.Now : end).ToString("MM/dd/yyyy HH:mm:ss"),
                        NowTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"),
                        NextStart = (nest == null ? issue.EndTime : nest.StartTime).ToString("MM/dd/yyyy HH:mm:ss")
                    };
                }
                else
                {
                    if (nest != null)
                    {
                        obj = new
                        {
                            nest.ID,
                            Number = nest.FormatIssueName,
                            StartTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"),
                            EndTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"),
                            NowTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"),
                            NextStart = nest.StartTime.ToString("MM/dd/yyyy HH:mm:ss"),
                        };
                    }
                }
            }

            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        public JsonResult LastWinNumber(int id)
        {
            object obj = null;
            IssueManage IM = new IssueManage();
            var issue = IM.GetPriorIssue((LotteryType)id);
            if (issue != null)
            {
                obj = new
                {
                    issue.ID,
                    Number=issue.FormatIssueName,
                    issue.OpenCode,
                    issue.State
                };
            }
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult OpenCodeHistory(int id,int? page)
        {
            int sz=18;
            if (id == (int)LotteryType.TC11X5)
                sz = 10;
            IssueManage IM = new IssueManage();
            var issues=IM.Select(s => s.
                OrderByDescending(p => p.StartTime).
                Where(p => p.LotteryID == id && p.State == (short)IssueState.Opened).
                Skip((page.HasValue ? page.Value : 0) * sz).Take(sz).ToArray());

            ModelNameValue<string, string> model = new ModelNameValue<string, string>();
            model.AddRange(issues.ToNameValue(p => p.FormatIssueName, p => p.OpenCode));
            ViewData["LotteryID"] = id;
            return PartialView(model);
        }

        public ActionResult More(LotteryType? id,PageInfo Page)
        {
            if (id.HasValue)
            {
                if (Page == null)
                    Page = new PageInfo();
                IssueManage im = new IssueManage();
                var issues = im.Select(s => s.Where(p => p.LotteryID == (int)id.Value&&p.State==(short)IssueState.Opened));
                Page.SunCount = issues.Count();
                ModelNameValue<string, Issue> model = new ModelNameValue<string, Issue>(issues.OrderByDescending(p=>p.StartTime).Skip((Page.CurrPage-1)*Page.PageCount).Take(Page.PageCount).ToList()
                    .ToNameValue(p=>Issue.PastIssueName((LotteryType)p.LotteryID,p.Number),p=>new Issue{ OpenCode=p.OpenCode,StartTime=p.StartTime}));
                ViewData["LotteryTypeID"] = id.Value;
                ViewData["More_PageInfo"] = Page;
                ViewData["LotteryTypeList"] = CacheManage.Lottery.Select(p => new SelectListItem {Selected=p.Value.ID==(int)id.Value,Text=p.Value.Name,Value=p.Key.ToString() });
                return View(model);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult Protocol(string id)
        {
            ViewData["Protocol"] = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_BetProtocol].Value;
            if ("uc".Equals(id, StringComparison.CurrentCultureIgnoreCase))
                return PartialView("Protocol_uc");
            return View();
        }

        public JsonResult WinMoneyList(LotteryType id)
        {
            var PM = new PlayTypeOptionManage();
            var list = PM.GetUserOptionByRatio(LoginUser.UserID, (int)id, LoginUser.WinModelID, LoginUser.Ratio)
                .Select(p => new
                    {
                        p.PlayTypeID,
                        p.PlayTypeListID,
                        p.WinMoney,
                        p.BackMoneyRatio,
                        p.BackMoneyToWinMoneyRatio,
                        p.MaxBackMoneyToWinMoney,
                    });
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Vedio(LotteryType id)
        {
            if (Request.UrlReferrer == null || Request.UrlReferrer.Host != Request.Url.Host)
                return new EmptyResult();
            var l = CacheManage.Lottery[id];
            var model = new VedioModel
            {
                LotteryID=l.ID,
                LotteryName=l.Name,
                OpenCodeLen=l.OpenCodeLength,
            };
            return View(model);
        }
    }
}
